import { defineComponent, ref, computed, } from "vue"
import { NModal, NButton, NCard, NIcon, NGi, NInput, NFormItem, NSpace, NCheckbox, NCheckboxGroup, NResult, NTag, } from "naive-ui"
import { CloseOutlined, FullscreenOutlined } from "@vicons/antd"
import useEditModel from "@/hooks/editModel"
import Flexform, { flexformitem, meiyongfunc, } from "@/components/flexform/index"
import { SearchOutlined, PlusOutlined, } from "@vicons/antd"
import { ViewFilled, Edit, Delete, ResetAlt, } from "@vicons/carbon"
import useHttpMessage from "@/hooks/oftenattr";
import MarkdownText from "@/components/markdown/index"
import TagselectDialog from "./tagselect"
export default defineComponent({
    name: "editModel",
    props: {
        close: {
            type: Function,
            default: null,
        },
    },
    setup({ close }, { expose, emit }) {
        /**********************************************************************************
        * 复用公共的钩子函数区域
        ***********************************************************************************/
        const { http, message } = useHttpMessage()
        const {
            showModel,
            handleInit,
            handleClose,
            handleReset,
            formValue,
            formRef,
            title,
            editType,
            resultText,
            loading,
            getSuccess,
            getFaild,
            handleReturn,
            result,
        } = useEditModel(null, null, "", close)
        expose({ handleInit, handleClose, handleReset, formValue })
        /**********************************************************************************
        * 自定义属性方法区域
        ***********************************************************************************/
        // 标签选择弹窗
        const tagselectRef = ref<any>(null)
        // 点击保存
        const handleSave = () => {
            formRef.value?.jiaoyan(() => {
                http.testquestionadd(formValue.value, loading).then((res: any) => {
                    if (res.data.success) {
                        getSuccess(res.data.msg || "创建成功")
                        setTimeout(() => {
                            handleClose()
                        }, 500)
                    } else {
                        getFaild(res.data.error || res.data.msg || "创建失败")
                    }
                }).catch(err => {
                    getFaild(err.message || "系统错误")
                })
            })
        }
        // 显示选择标签的弹窗
        const showtagDialog = () => {
            console.log("显示选择标签的弹窗");
            tagselectRef.value.handleInit("add")
        }
        // 删除标签
        const deletetag = (index: number) => {
            formValue.value["tags"]!.splice(index, 1)
        }
        // 表单配置
        const formList = ref([
            {
                span: 24,
                show: true,
                label: "标题",
                key: "title",
                default: "",
                type: "input",
                placeholder: "请输入标题",
                rules: [
                    { required: true, message: "请输入标题", trigger: ["blur", "change"], },
                    { max: 200, min: 2, message: "请输入2-200位字符", trigger: ["blur", "change"], },
                ],
            },
            {
                span: 24,
                show: true,
                label: "是否是顶级分类",
                key: "type",
                type: "select",
                placeholder: "请选择类型",
                rules: [
                    { required: true, message: "请选择类型", trigger: ["blur", "change"], },
                ],
                options: [
                    { label: "是", value: "1" },
                    { label: "否", value: "0" },
                ],
            },
            {
                span: 24,
                show: false,
                label: "父级分类",
                key: "parent",
                type: "cascader",
                placeholder: "请选择父级分类",
                rules: [
                    { required: true, message: "请选择父级分类", trigger: ["blur", "change"], },
                ]
            },
            {
                span: 24,
                show: true,
                label: "内容",
                key: "content",
                type: "slot",
                placeholder: "请输入内容",
                rules: [
                    { required: true, message: "请选择父级分类", trigger: ["blur", "change"], },
                ],
                slot: (formitem: flexformitem, shuaxin: Function) => <NFormItem label={formitem.label + "："} path={formitem.path || formitem.key} rule={formitem.rules || []}>
                    <MarkdownText />
                </NFormItem>
            },
            {
                span: 24,
                show: true,
                label: "文章标签",
                key: "tags",
                type: "slot",
                slot: (formitem: flexformitem, shuaxin: Function) => <NFormItem label={formitem.label + "："} path={formitem.path || formitem.key} rule={formitem.rules || []}>
                    <div class="w-full">
                        <NButton type={"info"} onClick={showtagDialog}>点击选择标签</NButton>
                        {Array.isArray(formValue.value["tags"]) ? formValue.value["tags"].map((item, index) => {
                            return <NTag closable={true} onClose={() => deletetag(index)}>{item.name}</NTag>
                        }) : null}
                    </div>
                </NFormItem>
            },
        ])
        // 表单change回调
        const formChange = (key: string, val: any) => {
            switch (key) {
                case "type":
                    // 只有在非顶级组件的时候才显示
                    const item = formList.value.find(el => el.key === "parent")
                    if (item && formValue.value.type === "0") {
                        item.show = true
                    } else {
                        item.show = false
                    }
                    break;
            }
        }
        /**********************************************************************************
       * 渲染用插槽区域
       ***********************************************************************************/
        const actionSlot = () => (<div class="flex justify-end items-center my-1">
            <NButton onClick={handleClose}>关闭</NButton>
            {(result.value === "" && editType.value === "add") ? <NButton class="ml-10px" type={"info"}
                onClick={handleSave}>创建</NButton> : (result.value === "" && editType.value === "edit") ?
                <NButton class="ml-10px" type={"info"} onClick={handleSave}>修改</NButton> : null}
            {result.value === "failed" ?
                <NButton class="ml-10px" type={"primary"} onClick={handleReturn}>返回</NButton> : null}
        </div>)
        const defaultSlot = () => (<div class="w-full flex flex-col">
            {result.value === "" ? <NCard contentStyle={{ minWidth: "605px", }}>
                <Flexform ref={formRef} v-model={[formValue.value, "value"]} formList={formList.value} onChange={formChange} />
            </NCard> : result.value === "success" ? <NCard contentStyle={{ minWidth: "605px", }}>
                <NResult status={'success'} title={'成功'} description={resultText.value} />
            </NCard> : result.value === "failed" ? <NCard contentStyle={{ minWidth: "605px", }}>
                <NResult status={'error'} title={'错误'} description={resultText.value} />
            </NCard> : null}
            <TagselectDialog ref={tagselectRef} />
        </div>)
        /**********************************************************************************
       * 主渲染区域
       ***********************************************************************************/
        return () => (<NModal show={showModel.value} onUpdateShow={(val) => showModel.value = val} preset={"dialog"}
            title={title.value} showIcon={false} loading={loading.value}
            v-slots={{ action: actionSlot, default: defaultSlot, }}>
        </NModal>)
    },
})
